package com.cgy.wodeyigui.product.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cgy.common.constant.ProductConstant;
import com.cgy.wodeyigui.product.dao.AttrAttrgroupRelationDao;
import com.cgy.wodeyigui.product.dao.AttrGroupDao;
import com.cgy.wodeyigui.product.dao.CategoryDao;
import com.cgy.wodeyigui.product.entity.AttrAttrgroupRelationEntity;
import com.cgy.wodeyigui.product.entity.AttrGroupEntity;
import com.cgy.wodeyigui.product.entity.CategoryEntity;
import com.cgy.wodeyigui.product.service.CategoryService;
import com.cgy.wodeyigui.product.vo.AttrGroupRelationVO;
import com.cgy.wodeyigui.product.vo.AttrResoponceVo;
import com.cgy.wodeyigui.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgy.common.utils.PageUtils;
import com.cgy.common.utils.Query;

import com.cgy.wodeyigui.product.dao.AttrDao;
import com.cgy.wodeyigui.product.entity.AttrEntity;
import com.cgy.wodeyigui.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
@Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
@Autowired
    AttrGroupDao attrGroupDao;//
    @Autowired
    CategoryDao categoryDao;

@Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //attrEntity.setAttrName(attr.getAttrName());//将VO的数据存到PO（对数据库的数据）里面  可用BeanUtils.copeProperties属性替代
        BeanUtils.copyProperties(attr,attrEntity);//前提是VO跟PO的属性名是一一对应
        //1保存基本数据
        this.save(attrEntity);
        //2保存关联关系
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long cateLogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if(cateLogId!=0){
            queryWrapper.eq("cateLogId",cateLogId);
        }
        String  key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
        queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResoponceVo> voList = records.stream().map((attrEntity) -> {
            AttrResoponceVo attrResoponceVo = new AttrResoponceVo();
            BeanUtils.copyProperties(attrEntity, attrResoponceVo);
            if("base".equalsIgnoreCase(type)){
                //设置分类和分组的名字
                AttrAttrgroupRelationEntity attrId = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrId != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    attrResoponceVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }



            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResoponceVo.setCatelogName(categoryEntity.getName());
            }

            return attrResoponceVo;
        }).collect(Collectors.toList());
        pageUtils.setList(voList);

        return pageUtils;
    }

    @Override
    public AttrResoponceVo getAttrInfo(Long attrId) {
        AttrResoponceVo attrResoponceVo = new AttrResoponceVo();
        AttrEntity attrEntity = this.getById(attrId);
        //设置分组信息
        BeanUtils.copyProperties(attrEntity,attrResoponceVo);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(attrAttrgroupRelationEntity!=null){
                attrResoponceVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if(attrGroupEntity!=null){
                    attrResoponceVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //2:设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrResoponceVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity!=null){
            attrResoponceVo.setCatelogName(categoryEntity.getName());
        }

        return attrResoponceVo;
    }
    @Transactional
    @Override
    public void updateAttr(AttrResoponceVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //1:修改分组关联
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());


            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(count>0){

                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            }else{
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }

    }
    /*/
        根据分组id 查找关联的基本属性
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrids = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if(attrids == null || attrids.size()==0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrids);

        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        //attrAttrgroupRelationDao.delete(new QueryWrapper<>().eq("attr_id",1).eq("attr_group_id",2))
        //delete from pms_attr_attrgroup_relation where attr_id = 1 and attr_group_id= 1
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(collect);
    }

}